package apollo.generator.common.interceptor;

import apollo.generator.common.base.RR;
import apollo.generator.common.utils.IPUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * <Description>
 * 日志拦截器
 * @author Jun Lee
 * @version 1.0
 * @createDate 2020-03-27 18:15:36
 */
@Component
public class LogInterceptor implements HandlerInterceptor {
    private final static Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws IOException {
        MDC.put("requestId", UUID.randomUUID().toString().replaceAll("-", ""));
        logger.info("----------,{},----------", request.getRequestURI());
        logger.info("请求的方法:{}", request.getMethod());
        logger.info("请求IP地址:{}", IPUtils.getIpAddr(request));
        logger.info("客户端信息:{}", request.getHeader("user-agent"));
        logger.info("请求的字符编码:{}", request.getCharacterEncoding());
        Map<String, String[]> parameterMap = request.getParameterMap();
        String requestData = null;
        String contentType = request.getContentType();
        if (parameterMap.isEmpty() && StringUtils.isNotEmpty(contentType) &&
                !contentType.contains("multipart/form-data")) {
            requestData = IOUtils.toString(request.getInputStream(),"UTF-8");
        }else{
            requestData = JSONObject.toJSONString(parameterMap,true);
        }
        logger.info("请求参数:\r\n{}",requestData);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        logger.info("Results--->{}", JSON.toJSONString(RR.get()));
        RR.remove();
    }
}
